package com.fanxuankai.boot.log.autoconfigure;

import com.fanxuankai.boot.log.enums.StoreType;
import com.fanxuankai.boot.log.store.LogStore;
import com.fanxuankai.boot.log.store.LoggerLogStore;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

/**
 * @author fanxuankai
 */
@Conditional(LoggerLogStoreAutoConfiguration.LoggerCondition.class)
@ConditionalOnClass({LoggerFactory.class})
@ConditionalOnProperty(name = LogProperties.ENABLED, matchIfMissing = true)
public class LoggerLogStoreAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public LogStore logStore() {
        return new LoggerLogStore();
    }

    protected static class LoggerCondition extends SpringBootCondition {
        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            ConditionMessage.Builder message = ConditionMessage.forCondition("Log Store Logger Condition");
            Environment environment = context.getEnvironment();
            String keyValue = environment.getProperty(LogProperties.STORE_TYPE);
            // 默认为 Logger
            if (StringUtils.isEmpty(keyValue) || StoreType.LOGGER.name().equalsIgnoreCase(keyValue)) {
                return ConditionOutcome.match(message.foundExactly("provided private or symmetric key"));
            }
            return ConditionOutcome.noMatch(message.didNotFind("provided private or symmetric key").atAll());
        }
    }
}